package com.shandao.shangxiu.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
  
import android.util.Base64;
  
public class Rsa {
    private static final String RSA_PUBLICE =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJBOmahylSYN9CdxMXBirESskvfGsYmVvpNw8EgaHOFEm3CFoLye" + "\r" +
            "o9Jsct+mLQgD0uIktj61lrN0hO1nBqb/KYeC//wQapAs4Xbf0g+AdzgXANehpd87dcVJ8/" + "\r" +
            "pLopA6HAKcF8uXuFC8Wyg4F0ioFQ+yxjIJu7X/EU35L2Ej688QIDAQAB";
    private static final String ALGORITHM = "RSA";
  
    /**
     * 得到公钥
     * @param algorithm
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String algorithm,
            String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64.decode(bysKey,Base64.DEFAULT);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);
  
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(x509);
    }
  
    /**
     * 使用公钥加密
     * @param content
     * @return
     */
    public static String encryptByPublic(String content) {
    	String password = "";
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
  
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);
  
            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);
            password = byte2hex(output);
            return password;
  
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
  
    /**
    * 使用公钥解密
    * @param content 密文
    * @return 解密后的字符串
    */
    public static String decryptByPublic(String content) {
        try {
            PublicKey pubkey = getPublicKeyFromX509(ALGORITHM, RSA_PUBLICE);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, pubkey);
            InputStream ins = new ByteArrayInputStream(Base64.decode(content,Base64.DEFAULT));
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            byte[] buf = new byte[128];
            int bufl;
            while ((bufl = ins.read(buf)) != -1) {
                byte[] block = null;
                if (buf.length == bufl) {
                block = buf;
                } else {
                block = new byte[bufl];
                for (int i = 0; i < bufl; i++) {
                    block[i] = buf[i];
                }
                }
                writer.write(cipher.doFinal(block));
            }
            return new String(writer.toByteArray(), "utf-8");
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
	 * byte数组转换成16进制字符串.
	 * 
	 * @param b
	 *            b
	 * @return String
	 */
	public static String byte2hex(byte[] b) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			result.append(hex.toLowerCase());
		}

		return result.toString();
	}
  
}

/**
 *
 * 在Cipher对象时，一定要指明使用RSA/ECB/PKCS1Padding，如：Cipher.getInstance("RSA/ECB/PKCS1Padding");
 * 打开rsa_public_key.pem文件，将上面代码的RSA_PUBLICE替换即可
 * 
 */